package com.hurui.xiaoming.fragment.main;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.hurui.xiaoming.R;
import com.hurui.xiaoming.activity.detailedlist.DetailedListActivity;
import com.hurui.xiaoming.activity.me.MyContractActivity;
import com.hurui.xiaoming.activity.me.MyDeailInfoActivity;
import com.hurui.xiaoming.activity.me.MyProgressActivity;
import com.hurui.xiaoming.bean.Li_IndexUI_Result;
import com.hurui.xiaoming.bean.Li_LoanApplication;
import com.hurui.xiaoming.bean.Li_Personal_Result;
import com.hurui.xiaoming.fragment.BaseFragment;
import com.hurui.xiaoming.myconfig.PamaryKeys;
import com.hurui.xiaoming.utils.DefultData;
import com.hurui.xiaoming.utils.WriteReadSharedPrefs;

import java.util.HashMap;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.hurui.xiaoming.utils.DefultData.loanApplication;

/**
 * Created by Administrator on 2017/7/10.
 */

public class HomeFragment extends BaseFragment {

    private View rootView ;
    //预借款
    TextView limitText;
    //借款进度条
    SeekBar limitProgress;
    //借款时间
    TextView borrowTime;
    //每月还款数
    TextView repaymentMoney;
    //借款时间进度条
    SeekBar borrowProgress;
    //我要还款
    LinearLayout repaymentLayout;
    //进度查询
    LinearLayout myProgress;
    //费用说明
    LinearLayout costIntrol;
    //申请借款
    Button application;

    int limitMoney = 10000;
    int limitTime = 3;
    int user_id = 0;

    int xiaoxi = 0;   //判断信息是否完善    1为完善   其他为不完善

    Map map = new HashMap();

    AlertDialog alertDialog;
    ImageView close;
    Button goFinish;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        if(rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_home, null);
            initView();

        }

        initAction();
        return rootView;
    }


    @Override
    public void onResume() {
        super.onResume();
        checkUserInfo();
    }

    @Override
    public void initView() {
        limitMoney = (int)(Float.parseFloat(WriteReadSharedPrefs.readUserLimit(mContext)));
        user_id = WriteReadSharedPrefs.readUserID(mContext);
        map.put("ui_type",3);
        map.put("ui_id",user_id);

        limitText = (TextView) rootView.findViewById(R.id.limitText);
        //设置显示的借款额度
        limitText.setText(String.valueOf(limitMoney));

        limitProgress = (SeekBar) rootView.findViewById(R.id.limitProgress);
        //设置最大进度值
        limitProgress.setMax((int)((float)limitMoney/100));
        limitProgress.setProgress((int)((float)limitMoney/100));

        borrowTime = (TextView) rootView.findViewById(R.id.borrowTime);
        //默认借款三个月
        borrowTime.setText(String.valueOf(limitTime));

        repaymentMoney = (TextView) rootView.findViewById(R.id.repaymentMoney);
        //每月还款
        updateMoney(limitMoney,limitTime);

        borrowProgress = (SeekBar) rootView.findViewById(R.id.borrowProgress);
        //最长借款12个月
        borrowProgress.setMax(12);
        borrowProgress.setProgress(3);

        repaymentLayout = (LinearLayout) rootView.findViewById(R.id.repaymentLayout);
        myProgress = (LinearLayout) rootView.findViewById(R.id.myProgress);
        costIntrol = (LinearLayout) rootView.findViewById(R.id.costIntrol);
        application = (Button) rootView.findViewById(R.id.application);
    }

    @Override
    public void initAction() {
        //预借款数额选择
        limitProgress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

                limitText.setText("" +  i*100);
                limitMoney = i*100;
                updateMoney(limitMoney,limitTime);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        //借款时间进度条
        borrowProgress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                if(i < 3){
                    i = 3;
                    borrowProgress.setProgress(1);
                }

                borrowTime.setText("" + i);
                limitTime = i;

                updateMoney(limitMoney,limitTime);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        //我要还款
        repaymentLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startDetailed(1);
            }
        });
        //进度查询
        myProgress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onOpen(new Intent(mContext , MyProgressActivity.class));
            }
        });
        //合同签署
        costIntrol.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext, MyContractActivity.class);
                onOpen(intent);
            }
        });

        //申请借款
        application.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                tishiKuang();
            }
        });
    }


    public float updateMoney(int money,int month){
        float m = (float) (((float) money/month) + (float) money*0.02);
        repaymentMoney.setText("每月还款" + fnum.format(m) + "元");
        return  m;
    }


    private void startDetailed(int index){
        Intent intent = new Intent(getActivity() , DetailedListActivity.class);
        intent.putExtra(PamaryKeys.state_flags , index );
        onOpen(intent);
    }

    /**
     * 前往信息完善界面
     */
    public void setDialog() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.go_finishuserinfo, null);
        close = (ImageView) view.findViewById(R.id.close);
        goFinish = (Button) view.findViewById(R.id.goFinish);

        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });
        goFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onOpen(new Intent(mContext , MyDeailInfoActivity.class));
                alertDialog.dismiss();
            }
        });

        alertDialog = new AlertDialog.Builder(mContext)
                .setView(view)
                .create();
        alertDialog.show();
    }

    /**
     * 借款成功弹框
     */
    public void setSuccessDialog() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.go_success, null);
        close = (ImageView) view.findViewById(R.id.close);
        goFinish = (Button) view.findViewById(R.id.goFinish);

        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });
        goFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // todo 查看借款进度
                onOpen(new Intent(mContext , MyProgressActivity.class));
                alertDialog.dismiss();
            }
        });

        alertDialog = new AlertDialog.Builder(mContext)
                .setView(view)
                .create();
        alertDialog.show();
    }

    /**
     * 用户信息正在审核中弹出框
     */
    public void setUserinfoIsFinish() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.userinfo_isfinish, null);
        close = (ImageView) view.findViewById(R.id.close);
        goFinish = (Button) view.findViewById(R.id.goFinish);

        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });
        goFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });

        alertDialog = new AlertDialog.Builder(mContext)
                .setView(view)
                .create();
        alertDialog.show();
    }

    /**
     * 检查信息是否完善
     */
    public void checkUserInfo(){
        Call<Li_IndexUI_Result> call = apiSevice.onHttpPostIndex(DefultData.indexData,map);
        call.enqueue(new Callback<Li_IndexUI_Result>() {
            @Override
            public void onResponse(Call<Li_IndexUI_Result> call, Response<Li_IndexUI_Result> response) {
                if(response.isSuccessful()){
                    Li_IndexUI_Result li_isUserFinish_result = response.body();
                    xiaoxi = li_isUserFinish_result.getXiaoxi();
                    if(xiaoxi == 3){
                        application.setText("客户信息正在审核中");
                    }
                }else{
                    onToast("失败1");
                }
            }

            @Override
            public void onFailure(Call<Li_IndexUI_Result> call, Throwable t) {
                onHttpFail( -1 , t.getMessage());
            }
        });
    }

    /**
     * 申请借款
     */
    public void loanApplication(){
        map.put("oi_jkprice",limitMoney);
        map.put("oi_jkloans",limitTime);
        if(xiaoxi == 1){
            Call<Li_LoanApplication> call = apiSevice.onHttpPostLoanApplication(loanApplication,map);
            call.enqueue(new Callback<Li_LoanApplication>() {
                @Override
                public void onResponse(Call<Li_LoanApplication> call, Response<Li_LoanApplication> response) {
                    if(response.isSuccessful()){
                        Li_LoanApplication li_isUserFinish_result = response.body();
                        if("sucess".equals(li_isUserFinish_result.getStatus())){
                            setSuccessDialog();
                            updateView();
                        }else if("noquota".equals(li_isUserFinish_result.getStatus())){
                            Toast.makeText(mContext,"额度不足",Toast.LENGTH_SHORT).show();
                        }else {
                            Toast.makeText(mContext,"借款失败",Toast.LENGTH_SHORT).show();
                        }
                    }else{
                        onToast("失败");
                    }
                }

                @Override
                public void onFailure(Call<Li_LoanApplication> call, Throwable t) {
                    onHttpFail( -1 , t.getMessage());
                }
            });
        }else if(xiaoxi == 2){
            setDialog();
        }else if(xiaoxi == 3){
            //todo 在用户信息正在审核状态下
            setUserinfoIsFinish();
        }
    }
    AlertDialog alertDialog1;
    public void tishiKuang(){
        alertDialog1 = new AlertDialog.Builder(mContext)
                .setTitle("确认")
                .setMessage("确定申请借款吗？")
                .setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        loanApplication();
                    }
                })
                .setNegativeButton("否", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        alertDialog1.dismiss();

                    }
                })
                .show();
    }

    public void updateView(){
        map.clear();
        map.put(PamaryKeys.UI_ID, WriteReadSharedPrefs.readUserID(mContext)+"");
        apiSevice.onHttpPostPersonal(map).enqueue(new Callback<Li_Personal_Result>() {


            @Override
            public void onResponse(Call<Li_Personal_Result> call, Response<Li_Personal_Result> response) {

                if (response.body().getStatus().equals("success")&& response.body().getData()!=null){
                    //设置显示的借款额度
                    limitText.setText(response.body().getData().getUi_limit());
                }
            }

            @Override
            public void onFailure(Call<Li_Personal_Result> call, Throwable t) {
                onHttpFail(0,t.getMessage());
            }
        });
    }
}
